<template>
  <div id="chatbox">
    <div class="chatbox" :class="{opensidebar: data.sidebar}">
      <div class="top">
        <div class="info">
          <div class="name">{{data.user.name ? data.user.name : data.user.nickname}}</div><br/>
          <div class="desc">{{data.csuser.wxname}} / 上次沟通 
            <Time :interval="1" :time="data.user.last_butt_time || 0" />
          </div>
        </div>
        <div class="openinfo" @click="data.sidebar = !data.sidebar">
          <Icons name="yonghutouxiang" />
        </div>
      </div>
      <div class="chat" @drop.prevent="dropImage">
        <Split v-model="split2" min="100px" mode="vertical" >
          <div slot="top" class="demo-split-pane">
            <div class="chat_list">
              <vue-scroll v-viewer @handle-resize="handleResize" ref="msg_list" :ops="msg_list.ops" class="msg_list_box">
                <center><a><font color="#2c90ff">查看更多消息</font></a></center>
                <msgItem v-for="(item, index) in data.chatlog" :key="index" :data="item" :user="data.user" :csuser="data.csuser"></msgItem>
                <div class="__bottom__" style="height:1px;"><!-- 列表最底部的定位 --></div>
              </vue-scroll>
            </div>
          </div> 
          <div slot="bottom" class="demo-split-pane">
              <div class="toolsbar">
                <div class="left">
                  <Poptip placement="top-start">
                    <Tooltip :transfer="true" placement="top" content="表情">
                    <div class="item"><Icons name="xiaolian" /></div>
                    </Tooltip>
                    <div slot="content" class="facelist">
                      <div class="img" v-for="(item, index) in face.list" :key="index">
                        <img :src="item.url" @click="addFace(index)">
                        <!--  @click="addFace(index)" -->
                      </div>
                    </div>
                  </Poptip>
                  <Tooltip :transfer="true" placement="top" content="图片">
                  <div class="item" @click="upLoadPic"><Icons name="tupian" /></div>
                  </Tooltip>
                  <Tooltip :transfer="true" placement="top" content="群发消息">
                  <div class="item"><Icons name="qunfaxiaoxi1" /></div>
                  </Tooltip>
                </div>
              </div>
              <div class="inputbox" 
                ref="inputbox" 
                @keydown="inputKeydown" 
                v-html="user.inputCont" 
                @input="printInfos" 
                contenteditable="true"
                @paste="inputPaste"></div>
              <div class="btn_list">
                <button class="send" @click="sendTextMsg">发送</button>
                <span>Shift + Enter 换行</span>
              </div>
          </div>
        </Split>
      </div>
    </div>
  </div>
</template>

<script>
  import facelist from '../../assets/data/face.json'
  import methods from './methods.js'
  import msgItem from '../msgItem'
  export default {
    name: 'chatBox',
    data: () => {
      return {
        split2: 0.7,
        face: {
          list: facelist
        },
        msg_list: {
          ops: {
            vuescroll: {
              mode: 'native'
            },
            scrollPanel: {
              initialScrollY: '100%',
              speed: 10
            },
            rail: {
              size: '3px',
              gutterOfSide: '0px'
            },
            bar: {
              background: '#3e58c9',
              opacity: 0.6
            }
          }
        },
        data: {
          sidebar: true,
          user: {},
          csuser: {},
          chatlog: []
        }
      }
    },
    components: {
      msgItem
    },
    props: {
      user: {
        default: {}
      },
      csId: {
        default: {}
      }
    },
    watch: {
      user () {
        this.loadUserInfo()
      },
      csId () {
        this.loadUserInfo()
      }
    },
    created () {
      window.$chatWin = this
      this.loadUserInfo()
    },
    methods: {
      // 加载用户资源
      async loadUserInfo () {
        console.log('改变用户')
        try {
          // 1.获取用户信息
          var user = await this.$fn.getSqlUser(this.user.openid)
          this.data.user = user
          // 2.获取客服信息
          var csuser = await this.$fn.getCuUser(this.csId)
          if (csuser.status !== 1) throw new Error('获取客服信息失败')
          this.data.csuser = csuser.cs_info
          // 3.获取聊天记录
          var chatlog = await this.$fn.getChatLog({
            cs_id: this.csId,
            openid: this.user.openid,
            last_time: parseInt(Date.now() / 1000)
          })
          this.data.chatlog = chatlog
        } catch (e) {
          console.log('失败', e.message)
        }
      },
      // 刷新消息列表滚动条
      handleResize () {
        this.$refs['msg_list'].refresh()
        this.$refs['msg_list'].scrollTo({
          y: '100%'
        })
      },
      // 上传图片
      upLoadPic () {
      },
      // 发送文字消息
      async sendTextMsg () {
        var src = this.$refs['inputbox'].innerHTML
        var imgReg = /<img.*?(?:>|\/>)/gi // 匹配img标签
        var altReg = /alt=['"]?([^'"]*)['"]?/i // 匹配alt属性
        var arr = src.match(imgReg)
        if (arr && arr.length > 0) {
          var text = this.$refs['inputbox'].innerHTML
          arr.forEach(function (item, index) {
            text = text.replace(/<img.*?(?:>|\/>)/, item.match(altReg)[1])
          })
          src = text
        }
        src = src.replace(/<br.*?(?:>|\/>)/gi, '\n\r')
        src = src.replace(/&nbsp;/gi, ' ')
        this.$refs['inputbox'].innerHTML = ''
        this.$refs['inputbox'].focus()
        var newstr = src || ''
        newstr = newstr.replace(/^(\s|\u00A0)+/, '').replace(/(\s|\u00A0)+$/, '')
        if (newstr === '') {
          this.$Message.warning('不能发送空白消息')
          return
        }
        var msg = {
          user_id: this.data.user.user_id,
          appid: this.data.csuser.appid,
          openid: this.data.user.openid,
          cs_id: this.data.csuser.id,
          type: 'text',
          content: src,
          send_type: 1002,
          send_time: Date.parse(new Date()) / 1000,
          send_state: 2
        }
        this.data.chatlog.push(msg)
        var index = this.data.chatlog.length - 1
        setTimeout(() => {
          this.$refs['msg_list'].scrollTo({
            y: '100%'
          })
          this.$refs['msg_list'].refresh()
        }, 0)
        var result = await this.$fn.sendMsgs(msg, this.data.user.user_id)
        if (result.status === 1) {
          var arrs = this.data.chatlog[index]
          arrs.send_state = 1
          this.$set(this.data.chatlog, index, arrs)
          this.$forceUpdate()
        }
        window.$chatBox.updataMsgUser(msg)
      },
      // 添加表情到输入框
      addFace (index) {
        this.$refs['inputbox'].focus()
        var msgText = '<img class="face" alt="' + this.face.list[index].value + '" src="' + this.face.list[index].url + '"/>'
        setTimeout(() => {
          methods._insertimg(this.$refs['inputbox'], msgText)
        }, 1)
      },
      // 输入框按键事件
      inputKeydown (event) {
        if (event.keyCode === 13 && !event.shiftKey) {
          event.preventDefault()
          this.sendTextMsg()
        }
        if (event.keyCode === 13 && event.shiftKey) {
          event.preventDefault()
          // var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode
          event.returnValue = false // 取消此事件的默认操作
          if (document.selection && document.selection.createRange) {
            var myRange = document.selection.createRange()
            myRange.pasteHTML('<br/>')
          } else if (window.getSelection) {
            var selection = window.getSelection()
            var range = selection.getRangeAt(0)
            range.collapse(true)
            range.deleteContents()
            var newP = document.createElement('br')
            range.insertNode(newP)
          }
        }
      },
      printInfos () {},
      // 输入框按键事件
      inputPaste () {
        var _this = this
        setTimeout(function () {
          var content = _this.$refs['inputbox'].innerHTML
          var valiHTML = ['br']
          content = content.replace(/_moz_dirty=""/gi, '')
            .replace(/\[/g, '[[-').replace(/\]/g, '-]]')
            .replace(/<\/ ?tr[^>]*>/gi, '[br]')
            .replace(/<\/ ?td[^>]*>/gi, '&nbsp;&nbsp;')
            .replace(/<(ul|dl|ol)[^>]*>/gi, '[br]')
            .replace(/<(li|dd)[^>]*>/gi, '[br]')
            .replace(/<p [^>]*>/gi, '[br]')
            .replace(new RegExp('<(/?(?:' + valiHTML.join('|') + ')[^>]*)>', 'gi'), '[$1]')
            .replace(new RegExp('<span([^>]*class="?at"?[^>]*)>', 'gi'), '[span$1]')
            .replace(/<[^>]*>/g, '').replace(/\[\[-/g, '[')
            .replace(/-\]\]/g, ']')
            .replace(new RegExp('\\[(/?(?:' + valiHTML.join('|') + '|img|span)[^\\]]*)\\]', 'gi'), '<$1>')
          content = content.replace(/\r?\n/gi, '<br>')
          _this.$refs['inputbox'].innerHTML = content
        }, 1)
      },
      // 拖拽图片上传
      dropImage (e) {
      },
      dropImage1 (e) {
        console.log(e.dataTransfer)
      }
    }
  }
</script>

<style lang="less">
  @import './style.less';
</style>
